package com.biwin.core.main.config;

import com.biwin.core.main.property.BiWinLoginProperties;
import com.biwin.core.main.property.BiWinSwaggerContactProperties;
import com.biwin.core.main.property.BiWinSwaggerProperties;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger3 Configration
 *
 * @author biwin
 * @since 0.0.1
 */
@Configuration
@EnableOpenApi
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
//@Profile(value = {"dev, test"})
public class SwaggerConfiguration {

    @Autowired
    private BiWinSwaggerProperties swaggerProperties;

    @Autowired
    private BiWinLoginProperties loginProperties;

    @Bean
    public Docket biwinCoreDocket() {
        return new Docket(DocumentationType.OAS_30)
                .enable(swaggerProperties.getEnable())
                .host(swaggerProperties.getHost())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/api/**")
                        .or(PathSelectors.regex(loginProperties.getCustomLoginUrl()))
//                        .or(PathSelectors.ant())
                        .or(PathSelectors.ant(loginProperties.getCustomLogoutUrl()))
                )
                .build().groupName("BiWin Framework")
                .apiInfo(coreApiInfo())
                //添加登录认证
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts("^(?!auth).*$"));
    }

    public static void main(String[] args) {
        System.out.println("/customLogin".matches("/customLogin"));
    }
    //配置多个Docket可以实现API分组
    @Bean
    public Docket projectBusinessDocket() {
        return new Docket(DocumentationType.OAS_30)
                .enable(swaggerProperties.getEnable())
                .host(swaggerProperties.getHost())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant(swaggerProperties.getAuthAntPath()))
                .build().groupName(swaggerProperties.getGroupName())
                .apiInfo(businessApiInfo())
                //添加登录认证
                .securitySchemes(securitySchemes())
                .securityContexts(businessSecurityContexts(swaggerProperties.getUnAuthAntPath()));
    }


    private ApiInfo coreApiInfo() {
        return new ApiInfoBuilder()
                .title("BiWin Framework 框架核心接口文档")
                .description("BiWin Framework 快速开发框架")
                .contact(new Contact("BiWin", "https://www.mybiwin.top", "274027703@qq.com"))
                .version("V0.0.1")
                .build();
    }

    private ApiInfo businessApiInfo() {
        BiWinSwaggerContactProperties contact = swaggerProperties.getContact();
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .contact(new Contact(contact.getName(), contact.getUrl(), contact.getEmail()))
                .version(swaggerProperties.getVersion())
                .build();
    }

    /**
     * 设置完成后进入SwaggerUI，右上角出现“Authorization”按钮，点击即可输入我们配置的认证参数。
     * 对于不需要输入参数的接口（上文所述的包含auth的接口），在未输入Authorization参数就可以访问。
     * 其他接口则将返回401错误。点击右上角“Authorization”按钮，输入配置的参数后即可通过认证访问。参数输入后全局有效，无需每个接口单独输入。
     * 通过Swagger2的securitySchemes配置全局参数：如下列代码所示，securitySchemes的ApiKey中增加一个名为“Authorization”，type为“header”的参数。
     * @return
     */
    private List<SecurityScheme> securitySchemes() {
        //设置请求头信息
        List<SecurityScheme> result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }


    private List<SecurityContext> securityContexts(String pathRegex) {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(getContextByPath(pathRegex));
        return securityContexts;
    }

    private List<SecurityContext> businessSecurityContexts(String pathRegex) {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(getContextByPath(pathRegex));
        return securityContexts;
    }

    private SecurityContext getContextByPath(String pathRegex) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    //设置Swagger3启用JWT的全局认证
    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = {authorizationScope};
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }
}
